<template>
  <div class="profile-detail">
    <!-- 头部 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="goBack">
          <svg t="1751614585251" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" 
            p-id="1471" width="20" height="20">
            <path d="M790.865959 73.216062 322.123178 512.062492l468.74278 438.746442c16.397998 16.697962 16.397998 43.894642 0 60.592603-16.397998 16.697962-42.894764 16.697962-59.292762 0l-498.839107-466.943c-8.698938-8.898914-12.398487-20.797461-11.898548-32.496033-0.599927-11.698572 3.099622-23.497132 11.898548-32.496033l498.839107-466.943c16.397998-16.697962 42.894764-16.697962 59.292762 0C807.263957 29.421409 807.263957 56.518101 790.865959 73.216062z" 
              fill="#272636" 
              p-id="1472">
            </path>
          </svg>
        </div>
        <div class="title">个人资料</div>
        <div class="placeholder"></div>
      </div>
    </div>

    <!-- 头像区域 -->
    <div class="avatar-section">
      <div class="avatar-container">
        <!-- 头像 -->
        <div class="avatar-wrapper">
          <div class="avatar" :style="avatarStyle" @click="previewAvatar()">
            <template v-if="!UserUpdateDTO.avatarUrl">
              {{ UserUpdateDTO.username ? UserUpdateDTO.username.charAt(0).toUpperCase() : '👤' }}
            </template>
          </div>
        </div>

        <!-- 用户名 -->
        <div class="username-display">{{ UserUpdateDTO.username }}</div>
        
        <!-- 操作按钮 -->
        <div class="btnBox">
          <!-- 头像选择 -->
          <el-upload
            ref="upload"
            v-model:file-list="fileList"
            class="uploadWrapper"
            accept="image/*"
            name="file"
            :action="path.baseUrl + '/common/file/uploadAvatar'"
            :auto-upload="false"
            :headers="UploadHeaders"
            :data="UploadData"
            :show-file-list="true"
            :multiple="false"
            :limit="1"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <!-- 触发文件选择框的内容 -->
            <template #trigger>
              <div class="avatar-edit-btn">
                <svg viewBox="0 0 24 24" width="16" height="16" style="margin-right: 5px;">
                  <path fill="currentColor" d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z" />
                </svg>
                更换头像
              </div>
            </template>
          </el-upload>

          <!-- 头像上传 -->
          <el-button v-show="fileList.length != 0" class="uploadBtn" @click="submitUpload">
            开始上传
          </el-button>
          
          <!-- 编辑资料 -->
          <div class="info-edit-btn" @click="handleEditInfo()" :style="{background: editFlag==false ? 'white' : '#a3e635'}">
            <svg t="1752847140437" viewBox="0 0 1066 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6373" width="16" height="16" style="margin-right: 5px;">
              <path d="M814.250631 1024H173.612841A174.005237 174.005237 0 0 1 0.000393 849.994763V228.99639A173.612448 173.612448 0 0 1 173.612841 54.991154h383.361424a39.278834 39.278834 0 0 1 0 78.557669H173.612841A95.054779 95.054779 0 0 0 78.558062 228.99639v620.998373a95.054779 95.054779 0 0 0 95.054779 95.447568h640.63779a95.054779 95.054779 0 0 0 95.05478-95.447568V483.130449a39.278834 39.278834 0 0 1 78.557669 0v366.864314a174.005237 174.005237 0 0 1-173.612449 174.005237z"
                p-id="6374" fill="#666"></path>
              <path d="M446.600741 663.813088a39.278834 39.278834 0 0 1-27.495185-11.390862 39.278834 39.278834 0 0 1-11.390861-32.994221l28.28076-212.498494a39.278834 39.278834 0 0 1 10.998074-22.388936l371.184986-373.148927a39.278834 39.278834 0 0 1 27.887972-11.390862 41.242776 41.242776 0 0 1 27.887973 11.390862l181.075426 182.253791a39.278834 39.278834 0 0 1 0 55.775945l-370.792197 372.756139a41.635565 41.635565 0 0 1-22.388936 10.998074l-209.356187 30.244703zM510.625241 432.067965l-19.639417 147.688417 144.938899-20.817782 334.262881-335.834035-125.69227-126.477847z"
                p-id="6375" fill="#666"></path>
            </svg>
            {{ editFlag==false ? '编辑资料' : '修改完毕' }}
          </div>
        </div>
        
      </div>
    </div>
    
    <!--信息区域-->
    <main class="main-content">
      <!-- 个人信息区域 -->
      <div class="info-section" v-if="editFlag==false">
        <div class="info-item">
          <div class="info-label">用户名</div>
          <div class="info-value">{{ UserUpdateDTO.username?.trim() || '未设置' }}</div>
          <div class="info-edit">></div>
        </div>
        
        <div class="info-item">
          <div class="info-label">用户ID</div>
          <div class="info-value">{{ UserUpdateDTO.id || '未设置' }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">个人简介</div>
          <div class="info-value">{{ UserUpdateDTO.bio?.trim() || '这个人很懒，还没有填写个人简介' }}</div>
          <div class="info-edit">></div>
        </div>
        
        <div class="info-item">
          <div class="info-label">性别</div>
          <div class="info-value">{{ formatGender(UserUpdateDTO.gender) }}</div>
          <div class="info-edit">></div>
        </div>
        
        <div class="info-item">
          <div class="info-label">生日</div>
          <div class="info-value">{{ formatDate(UserUpdateDTO.birthday) }}</div>
          <div class="info-edit">></div>
        </div>
        
        <div class="info-item">
          <div class="info-label">所在地</div>
          <div class="info-value">{{ UserUpdateDTO.location?.trim() || '未知' }}</div>
          <div class="info-edit">></div>
        </div>
      </div>
      <!--  个人信息区域（编辑）-->
      <div class="info-section" v-else-if="editFlag==true">
        <div class="info-item">
          <div class="info-label">用户名</div>
          <van-field v-model="UserUpdateDTO.username" label="" placeholder="请输入用户名" />
        </div>
        
        <div class="info-item">
          <div class="info-label">用户ID</div>
          <div class="info-value" style="cursor: not-allowed; color: #c8c9cc; opacity: 1;">{{ user_Store.userInfo.id || '未知' }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">个人简介</div>
          <van-field v-model="UserUpdateDTO.bio" placeholder="请输入个人简介" rows="1" type="textarea" :maxlength="50" show-word-limit autosize/>
        </div>
        
        <div class="info-item">
          <div class="info-label">性别</div>
          <van-radio-group v-model="UserUpdateDTO.gender" direction="horizontal">
            <van-radio :name=1 icon-size="14px">男</van-radio>
            <van-radio :name=2 icon-size="14px">女</van-radio>
            <van-radio :name=0 icon-size="14px">不愿透露</van-radio>
          </van-radio-group>
        </div>
        
        <div class="info-item">
          <div class="info-label">生日</div>
          <el-date-picker
            v-model="UserUpdateDTO.birthday"
            type="date"
            placeholder="请选择"
            size="default"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        
        <div class="info-item">
          <div class="info-label">所在地</div>
          <div class="info-value" style="cursor: not-allowed; color: #c8c9cc; opacity: 1;">{{ UserUpdateDTO.location || '未知' }}</div>
        </div>
      </div>


      <!-- 联系方式区域 -->
      <div class="contact-section" v-if="editFlag==false">
        <div class="section-title">联系方式</div>
        
        <div class="info-item">
          <div class="info-label">手机号</div>
          <div class="info-value">{{ formatPhone(UserUpdateDTO.phone) }}</div>
          <div class="info-edit">></div>
        </div>
        
        <div class="info-item">
          <div class="info-label">邮箱</div>
          <div class="info-value">{{ UserUpdateDTO.email?.trim() || '未设置' }}</div>
          <div class="info-edit">></div>
        </div>
      </div>
      <!-- 联系方式区域（编辑） -->
       <div class="contact-section" v-else-if="editFlag==true">
        <div class="section-title">联系方式</div>
        
        <div class="info-item">
          <div class="info-label">手机号</div>
          <van-field v-model="UserUpdateDTO.phone" label="" :disabled="true" />
        </div>
        
        <div class="info-item">
          <div class="info-label">邮箱</div>
          <van-field v-model="UserUpdateDTO.email" label=""/>
        </div>
      </div>


      <!-- 账号信息区域 -->
      <div class="account-section" v-if="editFlag==false">
        <div class="section-title">账号信息</div>
        
        <div class="info-item">
          <div class="info-label">注册时间</div>
          <div class="info-value">{{ formatDate(user_Store.userInfo.createTime) }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">账号状态</div>
          <div class="info-value">{{ formatStatus(user_Store.userInfo.status) }}</div>
        </div>
      </div>
      <!-- 账号信息区域（编辑） -->
       <div class="account-section" v-else-if="editFlag==true">
        <div class="section-title">账号信息</div>
        
        <div class="info-item">
          <div class="info-label">注册时间</div>
          <div class="info-value" style="cursor: not-allowed; color: #c8c9cc; opacity: 1;">{{ formatDate(user_Store.userInfo.createTime) || '' }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">账号状态</div>
          <div class="info-value" style="cursor: not-allowed; color: #c8c9cc; opacity: 1;">{{ formatStatus(user_Store.userInfo.status) || '' }}</div>
        </div>
      </div>


      <!-- 退出登录按钮 -->
      <div class="logout-section">
        <button class="logout-btn" @click="handleLogout()">退出登录</button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadFile, UploadFiles, UploadUserFile, UploadRawFile } from 'element-plus'
import { showImagePreview } from 'vant';
import 'vant/es/image-preview/style'; // showImagePreview是函数组件，要手动引入样式
import api from '@/api/index.js'
import path from '@/api/path'
import { CacheComponentStore } from '@/stores/cache/cacheComponentStore'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'

const router = useRouter()

const cache_Store = CacheComponentStore()
const user_Store = UserInfoStore()
const tip_Store = TipStore()

const editFlag = ref(false)
let originalUserInfo = null

// 用户信息
const UserUpdateDTO = ref({
  id: null,
  username: null,
  email: null,
  phone: null,
  password: null,

  avatarUrl: null,
  bio: null,
  gender: null,
  birthday: null,
  location: null,
  status: null,
})

// 头像样式
const avatarStyle = computed(() => {
  if (UserUpdateDTO.value.avatarUrl) {
    // 如果有头像URL，显示图片
    return {
      backgroundImage: `url(${UserUpdateDTO.value.avatarUrl})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center'
    }
  } else {
    // 如果没有头像，根据用户名生成渐变色
    const username = UserUpdateDTO.value.username || ''
    const charCode = username ? username.charCodeAt(0) : 0 // 获取用户名的第一个字符的 Unicode 编码
    const hue1 = (charCode * 5) % 360
    const hue2 = (hue1 + 40) % 360 // 在 hue1 基础上偏移 40 度，确保渐变色的两个颜色有对比
    
    return {
      // 使用 HSL 色彩模型（色相、饱和度 80%、亮度 65%）生成渐变色
      background: `linear-gradient(135deg, hsl(${hue1}, 80%, 65%), hsl(${hue2}, 80%, 65%))`
    }
  }
})

// 预览头像
const previewAvatar = ()=>{
  if(!UserUpdateDTO.value.avatarUrl){
    return
  }
  showImagePreview({
        images: [UserUpdateDTO.value.avatarUrl],
        startPosition: 0, // 指定图片的初始位置
        closeable: true // 显示关闭按钮
    });
}


// #region 头像上传
const upload = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([])

// 上传时附带的请求头
const UploadHeaders = ref({ 
  [user_Store.userJwtToken]: localStorage.getItem(user_Store.userToken) // 请求头名字，使用计算属性名，避免硬编码
})

// 上传时附带的额外参数
const UploadData = ref({ 
  userId: user_Store.userInfo?.id,
})

// 手动上传头像
const submitUpload = () => {
  upload.value!.submit()
}

// 图片移除时触发
const handleRemove: UploadProps['onRemove'] = async (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // console.log("列表移除文件时触发...")
}

// 文件上传前触发
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!rawFile.type.startsWith('image/')) {
        tip_Store.errorTip('文件必须为图片格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        tip_Store.errorTip('图片大小不能超过 1MB!')
        return false
    }
    return true
}

// 文件数量超出限制时触发
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  // 自动替换上一个文件
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

// 文件上传成功后触发
const handleUploadSuccess = async (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // 发送请求到后端，进行修改
  await api.User_UpdateAvatar(user_Store.userInfo.id, response.data) 
  upload.value!.clearFiles() // 移除上传完毕的文件
  tip_Store.successTip('修改成功！')

  // 更新前端用户信息
  user_Store.userInfo.avatarUrl = response.data
  UserUpdateDTO.value.avatarUrl = response.data
}

// #endregion


// 处理信息编辑
const handleEditInfo = async()=> {
  editFlag.value = !editFlag.value

  if(editFlag.value == false){
    if(!UserUpdateDTO.value.username.trim()){
      tip_Store.errorTip('用户名不能为空！')
    }
    if(!UserUpdateDTO.value.phone.trim()){
      UserUpdateDTO.value.phone = originalUserInfo.phone
    }
    if(!UserUpdateDTO.value.email.trim()){
      UserUpdateDTO.value.email = originalUserInfo.email
    }
    UserUpdateDTO.value.bio = UserUpdateDTO.value.bio.trim()

    // 如果修改前后UserUpdateDTO.value的各个属性值一致，则说明未修改，不发送请求
    if(JSON.stringify(originalUserInfo) == JSON.stringify(UserUpdateDTO.value)){
      return;
    }

    try{
      const updateRes = await api.User_Update(UserUpdateDTO.value) // 修改用户信息

      if(updateRes.data.code != 1){
        tip_Store.errorTip()
        return;
      }

      // 修改完成要强制重新刷新，重新使用jwt刷新用户信息
      let jwtToken = localStorage.getItem(user_Store.userToken);
      if(jwtToken != null){
        let jwtParseRes =  await api.User_GetUserInfoByJwt(jwtToken);
        if(jwtParseRes.data.code == 1){
          user_Store.setUserInfo(jwtParseRes.data.data); // 将用户信息存入pinia仓库
        }
      }

      // 拷贝用户信息
      Object.keys(UserUpdateDTO.value).forEach(key => {
        if (user_Store.userInfo.hasOwnProperty(key)) {
          UserUpdateDTO.value[key] = user_Store.userInfo[key];
        }
      });
      tip_Store.successTip()
  
    }
    catch(error){
      console.log("发生错误：",error)
    }
    finally{
      originalUserInfo = JSON.parse(JSON.stringify(UserUpdateDTO.value)) // 无论API调用成功与否，都更新originalUserInfo
    }

  }
}


// #region 辅助函数
// 返回上一页
function goBack() {
  router.go(-1)
}
// 格式化性别
function formatGender(gender) {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '未设置'
  return dateStr.split(' ')[0]
}

// 格式化手机号
function formatPhone(phone) {
  if (!phone) return '未设置'
  // 隐藏中间4位
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 格式化账号状态
function formatStatus(status) {
  if (status === 1) return '正常'
  if (status === 0) return '封禁中'
  return '未知'
}

// 处理退出登录
function handleLogout() {
  // 显示确认对话框
  if (confirm('确定要退出登录吗？')) {
    user_Store.clearUserInfo() // 清除用户信息
    cache_Store.reload('Profile', 'index') // 刷新个人主页组件
    cache_Store.reload('Home', 'index') // 刷新首页组件
    router.push('/Index/Profile') // 跳转页面
  }
}
// #endregion 


onMounted(() => {
  // 如果用户未登录，跳转到登录页
  if (!user_Store.userInfo?.id) {
    router.push('/login')
  }
  // 拷贝用户信息
  Object.keys(UserUpdateDTO.value).forEach(key => {
    if (user_Store.userInfo.hasOwnProperty(key)) {
      UserUpdateDTO.value[key] = user_Store.userInfo[key];
    }
  });
  // 使用深拷贝来存储原始用户信息，避免引用问题
  originalUserInfo = JSON.parse(JSON.stringify(UserUpdateDTO.value))
})


</script>

<style lang="scss" scoped>
.profile-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 头部样式 */
.header {
  background: white;
  padding: 12px 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  font-size: 20px;
  cursor: pointer;
  text-decoration: none;
  color: #333;
  width: 30px;
}

.title {
  font-size: 18px;
  font-weight: 500;
  flex: 1;
  text-align: center;
}

.placeholder {
  width: 30px;
}

/* 主内容区域 */
.main-content {
  padding: 0 15px 30px;
}

/* 头像区域 */
.avatar-section {
  background: white;
  padding: 30px 0 20px;
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  margin-top: 50px;
}

.avatar-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-wrapper {
  position: relative;
  margin-bottom: 20px;
  filter: drop-shadow(0 4px 8px rgba(0,0,0,0.1));
}

.avatar {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff6b6b, #ffa500);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36px;
  border: 3px solid white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  object-fit: cover;
}

.avatar:hover {
  cursor: pointer;
  transform: scale(1.02);
  box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

.avatar-wrapper:hover .avatar-edit-icon {
  opacity: 1;
}

.btnBox {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.uploadWrapper{
  max-width: 105px;
}

.avatar-edit-btn {
  background: #ff6b6b;
  color: white;
  font-size: 13px;
  padding: 6px 14px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s, transform 0.2s;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.uploadBtn{
  padding: 6px 14px;
  border-radius: 16px;
   margin-bottom: 10px;
}

.info-edit-btn {
  color: #666;
  border: 1px solid #ddd;
  font-size: 13px;
  padding: 6px 14px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s, transform 0.2s;
  margin-bottom: 10px;
}

.avatar-edit-btn:hover {
  background: #ff5252;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.uploadBtn:hover{
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(218, 216, 216, 0.4);
}

.info-edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(218, 216, 216, 0.4);
}

.avatar-edit-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.2);
}

.username-display {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

/* 信息区域通用样式 */
.info-section,
.contact-section,
.account-section {
  background: white;
  margin-bottom: 10px;
  padding: 0 15px;
}

.section-title {
  padding: 15px 0 5px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.info-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  width: 80px;
  color: #666;
  font-size: 14px;
}

.info-item > .van-cell {
  padding: 0;
}

.info-value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.info-edit {
  color: #999;
  font-size: 16px;
  cursor: pointer;
}

/* 退出登录按钮 */
.logout-section {
  padding: 20px 15px;
}

.logout-btn {
  width: 100%;
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 12px 0;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.logout-btn:hover {
  background: #ff5252;
}
</style>